package com.fept.msgcore.msgserver.protocol.util.crypto;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;

/**
 * Created by Srma on 2/9/2017.
 */
public class DESUtil {
    protected static final String DES = "DES";
    protected static final String DES_EDE = "DESede";

    public DESUtil() {
    }

    public static byte[] encrypt3DES(byte[] key, byte[] data) throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
        byte[] rawKey = new byte[24];

        for(int deskey = 0; deskey < rawKey.length; ++deskey) {
            rawKey[deskey] = key[deskey % key.length];
        }

        SecretKeySpec var5 = new SecretKeySpec(rawKey, "DESede");
        Cipher c1 = Cipher.getInstance("DESede");
        c1.init(1, var5);
        return c1.doFinal(data);
    }

    public static byte[] decrypt3DES(byte[] key, byte[] data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        byte[] rawKey = new byte[24];

        for(int deskey = 0; deskey < rawKey.length; ++deskey) {
            rawKey[deskey] = key[deskey % key.length];
        }

        SecretKeySpec var5 = new SecretKeySpec(rawKey, "DESede");
        Cipher c1 = Cipher.getInstance("DESede");
        c1.init(2, var5);
        return c1.doFinal(data);
    }

    public static byte[] decrypt(byte[] key, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        SecureRandom sr = new SecureRandom();
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(2, securekey, sr);
        return cipher.doFinal(data);
    }

    public static byte[] encrypt(byte[] key, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        SecureRandom sr = new SecureRandom();
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(1, securekey, sr);
        return cipher.doFinal(data);
    }
}
